package com.tt.vtg.controller;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.tt.vtg.dao.entity.User;
import static com.tt.vtg.exception.ExceptionConstants.*;
import com.tt.vtg.exception.VtgException;
import com.tt.vtg.service.UserService;
import com.tt.vtg.utils.JWTUtils;
import com.tt.vtg.utils.VtgUtils;

@RestController
public class IdentityManager {
	private final static long MIN = 60*1000;
	@Autowired
	@Qualifier("userSvc")
	private UserService userSvc;
	
	@RequestMapping(value="/auth", method=RequestMethod.POST)
	public String applyToken(@RequestBody User u, HttpServletResponse response){
		User user = userSvc.getUserEntityById(u.getUserId()).orElseThrow(()-> new VtgException(HttpServletResponse.SC_NOT_FOUND,RESOURCE_NOT_FOUND,"User id not found."));
		if(user.getPassword().equals(VtgUtils.encrypt(u.getPassword() + user.getSalt()))){
			return JWTUtils.createJWTByUser(userSvc.getById(u.getUserId()), 30*MIN);
		}
		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		throw new VtgException(HttpServletResponse.SC_UNAUTHORIZED,UNAUTHORIZED,"Password not correct.");
	}
}
